<template>
  <van-field name="switch" :label="label" label-align="top">
    <template #input>
      <div style="width: 100%; display: flex; flex-wrap: wrap">
        <template v-for="tag in tags" :key="tag">
          <van-tag
            type="primary"
            plain
            :closeable="!readonly"
            style="margin: 2vw 2vw 0 0"
            size="large"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </van-tag>
        </template>
        <van-tag v-if="!readonly" type="primary" size="large" style="margin-top: 2vw" @click="showInput">
          添加
        </van-tag>
      </div>
    </template>
  </van-field>
  <van-dialog
    v-model:show="showTagInputBox"
    :title="label"
    show-cancel-button
    @confirm="onTagConfirm"
    @cancel="onTagCancel"
  >
    <van-field v-model="tagInputValue" :placeholder="`请输入${label}`" />
  </van-dialog>
</template>

<script setup lang="ts">
let tagInputValue = ref('')
let showTagInputBox = ref(false)
let tags: Ref<Array<string>> = ref([])

const props = defineProps<{ label: string; tagList: Array<string>; readonly?: boolean }>()
const { label, readonly } = toRefs(props)

watch(
  () => props.tagList,
  (tagList) => (tags.value = tagList),
  { immediate: true }
)

const showInput = () => (showTagInputBox.value = true)

const emit = defineEmits<{
  (e: 'update:tagList', tagList: Array<string>): void
}>()

const handleClose = (removedTag: string) => {
  tags.value = tags.value.filter((tag: string) => tag !== removedTag)
  emit('update:tagList', tags.value)
}

const onTagConfirm = () => {
  const inputValue = tagInputValue.value
  let tagList = tags.value
  if (inputValue && tagList.indexOf(inputValue) === -1) tagList = [...tagList, inputValue]
  tags.value = tagList
  tagInputValue.value = ''
  emit('update:tagList', tags.value)
}

const onTagCancel = () => (tagInputValue.value = '')
</script>
